package msg

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"miners-monitor/models/common"
)

const dbName = "msg"

type MessageDbModel struct {
	common.BaseModel
	CommonFunc common.CommonFunc
}

func (this *MessageDbModel) FindOne(filter Message, opts *options.FindOneOptions) *mongo.SingleResult {
	filterBsonByte, err := this.CommonFunc.BsonMarshal(filter)
	if err != nil {
		panic(err)
	}
	return this.MDB.Collection(dbName).FindOne(context.TODO(), filterBsonByte, opts)
}

func (this *MessageDbModel) Find(filter interface{}, opts *options.FindOptions) *mongo.Cursor {
	result, err := this.MDB.Collection(dbName).Find(context.TODO(), filter, opts)
	if err == mongo.ErrNoDocuments {
		return nil
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *MessageDbModel) Upsert(update Message) {
	filterBsonD, err := this.CommonFunc.StructToBsonD(Message{
		CID:    update.CID,
	})
	if err != nil {
		panic(err)
	}

	update.CID = ""
	updateBsonD, err := this.CommonFunc.StructToBsonD(update)
	if err != nil {
		panic(err)
	}
	opts := options.Update().SetUpsert(true)
	updateSet := bson.D{{"$set", updateBsonD}}
	_, err = this.MDB.Collection(dbName).UpdateOne(context.TODO(), filterBsonD, updateSet, opts)
	if err != nil {
		panic(err)
	}
}
